package com.shanghaionstar.test.api;

import com.onstar.cn.api.util.AuthUtils;
import com.onstar.cn.auth.AuthTokenRequestEntity;
import com.onstar.cn.auth.LoginEntity;
import com.onstar.cn.common.util.DeviceUtil;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.retrofit.Api.HttpManagerApi;
import com.shanghaionstar.retrofit.listener.HttpOnNextListener;
import com.shanghaionstar.retrofit.listener.HttpOnNextSubListener;
import com.shanghaionstar.test.service.HttpPostService;
import com.shanghaionstar.utils.BusinessUtil;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.security.InvalidKeyException;
import java.security.SignatureException;


/**
 * 多api共存方案
 * Created by WZG on 2017/4/13.
 */

public class AuthorizeApi extends HttpManagerApi {

    public AuthorizeApi(HttpOnNextListener onNextListener, RxAppCompatActivity appCompatActivity) {
        super(onNextListener, appCompatActivity);
        /*统一设置*/
        setCache(true);
    }

    public AuthorizeApi(HttpOnNextSubListener onNextSubListener, RxAppCompatActivity appCompatActivity) {
        super(onNextSubListener, appCompatActivity);
        /*统一设置*/
        setCache(true);
    }

    public void getAuthToken(LoginEntity loginEntity){
        AuthTokenRequestEntity entity = BusinessUtil.createAuthTokenRequestEntity();
        entity.setPassword(loginEntity.getPassword());
        entity.setUserName(loginEntity.getName());
        entity.setDeviceId(new DeviceUtil(OnstarApplication.getApplication()).getDeviceID());
        try {
            String jwtToken = AuthUtils.encodeForInitialAuth(loginEntity.getName(), loginEntity.getPassword(),
                    entity.getClientId(), entity.getDeviceId(), entity.getClientSecret(), entity.getScope());

            HttpPostService httpService = getRetrofit().create(HttpPostService.class);
            doHttpDeal(httpService.authorizeToken(jwtToken));
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        }

    }








}
